# -*- coding: utf-8 -*-
# @Time    : 2020/10/19 22:36
# @Author  : liupengfei
# @File    : serializers.py
from rest_framework import serializers
from .models import BargainActivity, BargainActivityApply, MemberBargainRecord


class BargainActivityApplyListSerializer(serializers.ModelSerializer):
    face = serializers.CharField(source='member_activity.member.face_url', read_only=True)
    gender = serializers.CharField(source='member_activity.member.gender', read_only=True)

    class Meta:
        model = BargainActivityApply
        fields = ('face', 'gender')


class BargainActivityApplyDetailSerializer(serializers.ModelSerializer):
    progress = serializers.SerializerMethodField()
    apply_phoneNumber = serializers.SerializerMethodField()
    is_bargain = serializers.SerializerMethodField()
    activity_status = serializers.CharField(source='member_activity.get_status_display')

    def get_is_bargain(self, obj):
        # 是否砍过了
        member_bargain_record = MemberBargainRecord.objects.filter(bargain_activity=obj,
                                                                   member=self.context['request'].user.member)
        if member_bargain_record:
            return True
        return False

    def get_apply_phoneNumber(self, obj):
        # 报名者的手机号
        return obj.member_activity.member.phoneNumber

    def get_progress(self, obj):
        # 砍价进度
        activity = obj.member_activity.activity
        activity_bargain = BargainActivity.objects.filter(activity=activity).first()

        return round(obj.has_bargain_amount * 100 / activity_bargain.old_price, 2)

    class Meta:
        model = BargainActivityApply
        fields = ('has_bargain_amount', 'remain_amount', 'apply_phoneNumber', 'end_time', 'progress', 'is_bargain',
                  'activity_status')


class MemberBargainRecordListSerializer(serializers.ModelSerializer):
    face_url = serializers.CharField(source='member.face_url', read_only=True)
    nickname = serializers.SerializerMethodField()

    def get_nickname(self, obj):
        nickname = obj.member.user.nickname
        if nickname:
            return nickname[0] + '*' * len(nickname) + nickname[-1]
        return '******'

    # 砍价活动记录列表
    class Meta:
        model = MemberBargainRecord
        fields = ('amount', 'face_url', 'create_time', 'nickname')


class BargainActivityDetailSerializer(serializers.ModelSerializer):
    # 砍价活动详情
    class Meta:
        model = BargainActivity
        fields = ('coupon_count', 'remain_count', 'old_price', 'new_price')


class BargainActivitySerializer(serializers.ModelSerializer):
    # 创建活动
    class Meta:
        model = BargainActivity
        fields = '__all__'


class BargainActivityApplySerializer(serializers.ModelSerializer):
    # 报名活动
    class Meta:
        model = BargainActivityApply
        fields = '__all__'
